Consider the following variables, and the function $f$.
In [11]:
x = 1
y = 2
def f():
x = 3
y = 4
What will happen when we call the function $f$... what will the values of x and y be after the function call?
In [12]:
f()
print(x, y)
So, how many variables are there?
In [19]:
x = 1
y = 2
def make_closure():
x = 3
y = 4
def f():
print(x, y)
return f
In [20]:
c = make_closure()
c()
In [22]:
x, y
Out[22]:
In [23]:
c()
In [1]:
x = 5
y = 13
def make_closure():
x = 42
y = 911
def func():
global x # sees the global value
print(x, y)
x += 1
return func
In [ ]:
def make_closure():
value = 0
def get_next_value():
nonlocal value
value += 1
return value
return get_next_value